package coreAlgorithm.command;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import coreAlgorithm.NodeTriple;

public class FindValueResponse extends Response {

	private final List<NodeTriple> responseList;
	private final Serializable value;
	
	public FindValueResponse(Serializable value) {
		super();
		this.value = value;
		this.responseList = null;
	}

	public FindValueResponse(List<NodeTriple> responseList) {
		super();
		this.responseList = responseList;
		this.value = null;
	}
	
	public List<NodeTriple> getResponseList() {
		return responseList;
	}
	
	public Serializable getValue() {
		return value;
	}

	@Override
	public Response clone() {
		List<NodeTriple> newList;
		Serializable newValue;
		if(responseList != null) {
			newList = new ArrayList<NodeTriple>();
			for (Iterator<NodeTriple> iter = responseList.iterator(); iter.hasNext();) {
				NodeTriple nodeTriple = (NodeTriple) iter.next();
				newList.add(nodeTriple.clone());
			}
			return new FindValueResponse(newList);
		}
		if(value != null) {
			try {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(baos);
				oos.writeObject(value);
				oos.flush();
				ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
				newValue = (Serializable) ois.readObject();
				
			} catch (Exception e) {
				throw new RuntimeException("The cloning of the stored value wasn't feasible", e);
			} 
			return new FindValueResponse(newValue);
		}
		throw new RuntimeException("Could'n clone, since response list and stored value are null. At least one has to be initialized!");
	}

}
